/*==============================================================================
IV ESTIMATES

Date	: 2021-03-02
Creator	: Jonas Cederlof	(JC)
Description : 
Notes:
==============================================================================*/
clear
set more			 off
cap   log close 		_all
log using 	"../log/E1_firststage.log" 	, replace 
use 		"$datapath/E1_largesample.dta"	, clear

* Keep the main analysis sample along with their white-collar coworkers 
keep if bw5258==1 & age_def!=55 

{ // Indicate first observations of new job
*===============================================================================
*Condtion on newfirm==1 and observred wage (post eventtime>=0 by construction)
bys lopnr (eventtime_def) : gen nvals = sum(newfirmid!=. & manl_newfirm!=. & newfirmid==firstnewfirmid) if newfirmid!=. & manl_newfirm!=. & newfirmid==firstnewfirmid
gen xnvalsdate = date if nvals==1 
bys lopnr (eventtime_def) : egen nvalsdate = max(xnvalsdate) // impute for all obs this value
format nvalsdate %tm

*Generte same as above but correct for observing the wage possibly earlier
bys lopnr (eventtime_def) : gen nvals2 = sum(1) if firmid_lonestruktur==firstnewfirmid & eventtime_def>=0 & firmid_lonestruktur!=.
gen xnvals2date = date if nvals2==1 
bys lopnr (eventtime_def) : egen nvals2date = max(xnvals2date) // impute for all obs this value
format nvals2date %tm

*Indicate first wage from new firm in wage survey (no matter the firm and RAMS indicators)
bys lopnr (eventtime_def) : gen nvals4 = sum(1) if firmid!=firmid_lonestruktur & firmid_lonestruktur!=. & eventtime_def>=0

*Pre wage from notifying firm (last observred wage at notifying firm before or at notification)
bys lopnr (eventtime_def) : gen nvals3 = _n if manl!=. & date<=nvalsdate & eventtime_def<=0
bys lopnr (eventtime_def) : egen maxnvals3 = max(nvals3)

*Date for last wage at notifying firm
gen xnvals3date = date if nvals3==maxnvals3	& nvals3!=. & inrange(eventtime_def,-24,0)
bys lopnr (eventtime_def) : egen nvals3date = max(xnvals3date)
format nvals3date %tm

*Difference in time between old and new wage
gen diff = nvalsdate - nvals3date
sum diff if nvals==1

*Wage at notifying firm	
gen xprewage = manl if date==nvals3date 
bys lopnr (eventtime_def) : egen prenotfwage = max(xprewage)
drop xprewage

*fixa sa att datumet for gamla lonen inte far vara efter nya jobbet fas (i.e date of nvals3 < date of nvals)

*Generate eventtime for wage growth (i.e time after having found new job)
bys lopnr (eventtime_def) : gen timeafterjob = sum(1) if nvals>=1 & date>= nvalsdate


}
*
{ // Generate wages
*===============================================================================
*Generate log wage variables 
gen log_manl_newfirm = log(manl_newfirm)
gen log_manl_newfirm2 = log(manl_notfirm_specific)
gen diff_log_manl_newfirm = log(manl_newfirm) - log(prenotfwage)
gen diff_log_manl_newfirm2 = log(manl_notfirm_specific) - log(prenotfwage)

*Generate wage growth per year
gen firstnewwage = manl_newfirm if nvals==1
bys lopnr (eventtime_def) : egen fill_manl_newfirm = max(firstnewwage) 
bys lopnr (eventtime_def) : gen wgrowth = log(manl_newfirm) - log(fill_manl_newfirm)


}
*
{ // Generate: Event time to displacement
*===============================================================================
bys lopnr (date) : gen lastmonthwork =  date if  atfirm2[_n-1]==1 & atfirm2==1 & atfirm2[_n+1]==0  & atfirm2[_n+2]==0 
format lastmonthwork %tm

bys lopnr (date) : gen SPnvals = sum(1) 	if lastmonthwork!=.
tab SPnvals 				if lastmonthwork!=.
bys lopnr : egen maxnvals = max(SPnvals)

*Take away displacemnt dates that occur 12 months before notification for those with multiple displacments dates
replace lastmonthwork=. if eventtime_def<-12 & maxnvals>1


bys lopnr (date) : gen SPnvals2 = sum(1) 	if lastmonthwork!=.
tab SPnvals2 				if lastmonthwork!=.
bys lopnr : egen maxnvals2 = max(SPnvals2)
*Now 93.87 percent are displaced only once

 gen SPdiff = lastmonthwork - notdate_def
 
*So very few do not work 12 months prior to notification so we get rid of these
replace lastmonthwork=. if eventtime_def<-12
drop SPdiff

   
*Taking the minimum date assures that we get the nvals==1 as displacement date
fastmin lastmonthwork , by(lopnr) name(dispdate)
replace dispdate = dispdate +1
format dispdate %tm

*Recalls (working 3 months after displacement event has occured)
bys lopnr (date) : gen xrecalldate = date if atfirm2[_n-2]==0 & atfirm2[_n-1]==0 & atfirm2==1 & atfirm2[_n+1]==1 & atfirm2[_n+3]==1 & date>dispdate
fastmin xrecalldate , by(lopnr) name(recalldate)
format recalldate %tm
drop x*
gen recalled = recalldate!=.   
   
*Generate: Month of displacement
gen monthofdisp = month(dofm(dispdate))

*Generate: Months worked after notification
gen RAMSmonths = dispdate - notdate_def

*Generate: Displacement event time
bys lopnr (date) : gen dispeventtime = date - dispdate

*Generate: Months working at notifying firm in a year
bys lopnr year (date) : egen monthsatfirm = total(atfirm2)

}
*

*Merge on severance payments
merge m:1 lopnr dispeventtime using "$datapath/SP.dta"
drop if _merge==2
drop _merge
replace SP5_win_1_99=SP5_win_1_99/1000
bys lopnr : egen SP5IV = max(SP5_win_1_99)

*Generate 1-digit industry FE
tab SNI_1dig , gen(D_SNI_1dig)

*Generate flexible controls
gen avg_tenure_layoff_sq = avg_tenure_layoff^2
gen avg_age_layoff_sq = avg_age_layoff^2

*Replace Y/M FE:s to vary by main sample
replace ym_def = ym_def*ageCUT_52

{ // Define globals
*===============================================================================
global covariets 	"c.C_annual_ear_prenot_def##i.ageCUT_52 c.C_female##i.ageCUT_52 c.C_immigrant##i.ageCUT_52 c.C_tenureatnot##i.ageCUT_52 c.C_educ0##i.ageCUT_52  c.C_educ1##i.ageCUT_52 c.C_educ2##i.ageCUT_52 c.C_educ3##i.ageCUT_52 "	
global covariets2 	" 					c.C_female##i.ageCUT_52 c.C_immigrant##i.ageCUT_52 c.C_tenureatnot##i.ageCUT_52 c.C_educ0##i.ageCUT_52  c.C_educ1##i.ageCUT_52 c.C_educ2##i.ageCUT_52 c.C_educ3##i.ageCUT_52 "	
global firmcovar 	"firm_avg_age q_firm_age_RAMS firm_avg_earnings firm_avg_age firm_share_female firm_share_higheduc firm_noemployed_RAMS"	
global sizeFE 		"antvars avg_tenure_layoff* share_within*  "
global ageinnot		"WCshare_age_brack50*"
global instrument	"N_above55"
global linear		"ageFE* ageCUT*"
global quadratic	"$linear q_runvar q_inter"
global cubic 		"$quadratic c_runvar c_inter"
}
*
{ // First stage leave-out-mean graph (de facto AN) inc. blue-collars
*===============================================================================
preserve
	replace nottime_def=nottime_def/30
	keep if eventtime_def==0
	
	bys varselid: egen total = total(nottime_def)
	bys varselid: egen count = count(nottime_def)
	bys varselid: 	gen LOM = (total - nottime_def)/(count - 1)

	gen freq=1
	
	gen 	runvar 	= age_def-55
	gen  	treat  	= runvar>=0
	gen 	inter 	= runvar*treat

	
	local outcome "LOM"
	keep if inrange(age_def,52,58)
	count
	xtset ym_def
	xtreg `outcome' $instrument $linear $covariets, fe nonest cluster(varselid)
	local b = round(_b[$instrument] ,0.001)
	local se = round(_se[$instrument] ,0.002)
	
	*Residulize year*moth fixed effects
	areg `outcome' $covariets, absorb(ym_def)
	predict e, residuals
	sum `outcome' 
	replace `outcome' = e + r(mean)
	
	*Fix bins of runvar
	gen 	bin = round(runvar*12)
	egen 	bin2 = cut(bin) , at(-36(2)1)
	egen 	bin3 = cut(bin), at(1(2)36)
	gen 	bin4 = bin2
	replace bin4 = bin3 if bin4==.
	replace bin4 = bin4 + 0.5
	bys bin4: egen `outcome'_bin = mean(`outcome')
	qui tab  runvar bin4
	
	
	*local define
	local lineopt 	"lpattern(dash) lcolor(black) lstyle(foreground)"
	
	collapse (mean) `outcome' `outcome'_bin  (sum) freq, by(runvar bin4 treat)
	
	replace runvar = runvar*12
	
	*Linear Fit
	twoway 	(scatter `outcome'_bin  bin4 		 	 , ms(o) mcolor(black))  		///	 	
		(lfit 	 `outcome' runvar [aweight=freq] 	if treat==0, lcolor(black)) 	 		///
		(lfit 	 `outcome' runvar [aweight=freq] 	if treat==1, lcolor(black))	 		///
		, xline(0 , `lineopt')  legend(off) graphregion(color(white)) 					///
		  xscale(r(-36 36)) xlabel(-36(12)36)  ///
		  xtitle("Normalized age (months)") ytitle("Notification time of coworkers (months)")   ///
		  text( 5.7 12  "{&beta}=`b'*** (`se')"  ,place(right) )  ///
		  name(a,replace)
	graph export "$agegraphpath/RD/RD_`outcome'_NTcoworkers_all.pdf", replace
restore
}
*
keep if WC_at_not==1 & bw5258==1 & age_def!=55
{ // First stage leave-out-mean graph (de facto AN) only White-collar
*===============================================================================
preserve
	replace nottime_def=nottime_def/30
	keep if eventtime_def==0
	
	bys varselid: egen total = total(nottime_def)
	bys varselid: egen count = count(nottime_def)
	bys varselid: 	gen LOM = (total - nottime_def)/(count - 1)

	gen freq=1
	
	gen 	runvar 	= age_def-55
	gen  	treat  	= runvar>=0
	gen 	inter 	= runvar*treat

	
	local outcome "LOM"
	keep if inrange(age_def,52,58)
	count
	xtset ym_def
	xtreg `outcome' $instrument $linear $covariets, fe nonest cluster(varselid)
	local b = round(_b[$instrument] ,0.001)
	local se = round(_se[$instrument] ,0.002)
	
	*Residulize year*moth fixed effects
	areg `outcome' $covariets, absorb(ym_def)
	predict e, residuals
	sum `outcome' 
	replace `outcome' = e + r(mean)
	
	*Fix bins of runvar
	gen 	bin = round(runvar*12)
	egen 	bin2 = cut(bin) , at(-36(2)1)
	egen 	bin3 = cut(bin), at(1(2)36)
	gen 	bin4 = bin2
	replace bin4 = bin3 if bin4==.
	replace bin4 = bin4 + 0.5
	bys bin4: egen `outcome'_bin = mean(`outcome')
	qui tab  runvar bin4
	
	
	*local define
	local lineopt 	"lpattern(dash) lcolor(black) lstyle(foreground)"
	
	collapse (mean) `outcome' `outcome'_bin  (sum) freq, by(runvar bin4 treat)
	
	replace runvar = runvar*12
	
	*Linear Fit
	twoway 	(scatter `outcome'_bin  bin4 		 	 , ms(o) mcolor(black))  		///	 	
		(lfit 	 `outcome' runvar [aweight=freq] 	if treat==0, lcolor(black)) 	 		///
		(lfit 	 `outcome' runvar [aweight=freq] 	if treat==1, lcolor(black))	 		///
		, xline(0 , `lineopt')  legend(off) graphregion(color(white)) 					///
		  xscale(r(-36 36)) xlabel(-36(12)36)  ///
		  xtitle("Normalized age (months)") ytitle("Notification time of coworkers (months)")   ///
		  text( 6.3 12  "{&beta}=`b'* (`se')"  ,place(right) )  ///
		  name(a,replace)
	graph export "$agegraphpath/RD/RD_`outcome'_NTcoworkers_WConly.pdf", replace
restore
}
*
{ // Graphs of SP-spillover (column 3 in table above)
*===============================================================================
preserve
	keep if SP5_win_1_99!=.	
	*==========
	xtset   ym_def
	*==========
	*Below age 55
	 xtreg SP5_win_1_99 $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig if age_def<55, cluster(varselid) fe nonest
	local b = round(_b[shareabove55_LOM],0.01)
	local se = round(_se[shareabove55_LOM],0.01)
	binscatter SP5_win_1_99 shareabove55_LOM if age_def<55, controls($linear   $covariets $firmcovar $sizeFE i.SNI_2dig ) ///
	absorb(ym_def) ytitle("Severance pay (1,000 SEK)") xtitle("Share of co-workers above age 55") mc(black) ms(o) lc(black) ///
	text(120 0.1 "{&beta}=`b'***") text(118 .095  " (`se')") yscale(r(80 130)) ylab(80(10)130) name(a,replace)
	graph export "$agegraphpath/IV/SP_spillover_below55.pdf", replace
	*Above age 55
	qui xtreg SP5_win_1_99 $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig if age_def>55, cluster(varselid) fe nonest
	local b = round(_b[shareabove55_LOM],0.01)
	local se = round(_se[shareabove55_LOM],0.01)
	binscatter SP5_win_1_99 shareabove55_LOM if age_def>55, controls($linear   $covariets $firmcovar $sizeFE i.SNI_2dig ) ///
	absorb(ym_def) ytitle("Severance pay (1,000 SEK)") xtitle("Share of co-workers above age 55") mc(black) ms(o) lc(black) ///
	text(120 0.1 "{&beta}=`b'") text(118 .1  " (`se')") yscale(r(80 130)) ylab(80(10)130) name(b,replace)
	graph export "$agegraphpath/IV/SP_spillover_above55.pdf", replace
restore	
}
*
{ // BALANCE: Earnings (t-1)
*===============================================================================
preserve
keep if  eventtime_def==0 
replace annual_ear_prenot_def = annual_ear_prenot_def/1000

*Generate predicted earnings
areg annual_ear_prenot_def $covariets2, absorb(ym_def)
predict pred_ear, resid
qui sum annual_ear_prenot_def
replace pred_ear = pred_ear + `r(mean)'

*==========
xtset   ym_def
*==========
eststo clear
count if ageCUT_52==1  & C_female!=. & C_immigrant!=. & C_tenureatnot!=. & C_educ1!=. & C_educ2!=. & C_educ3!=. 
 eststo : xtreg annual_ear_prenot_def $instrument  $linear $covariets2 , cluster(varselid) fe nonest
		test   	$instrument 
qui estadd 	scalar 	Fstat  = r(F), replace
qui estadd 	local lin  	" $ \checkmark $ "  , replace
qui estadd 	local inter 	" $ \checkmark $ "  , replace
qui estadd 	local ym  	" $ \checkmark $  " , replace
qui estadd 	local covar 	" $ \checkmark $  " , replace

qui eststo :xtreg annual_ear_prenot_def $instrument shareabove55_LOM  $linear $covariets2  $sizeFE  , cluster(varselid) fe nonest
		test   	$instrument shareabove55_LOM
qui estadd 	scalar 	Fstat  = r(F), replace
qui estadd 	local lin  	" $ \checkmark $ " , replace
qui estadd 	local inter 	" $ \checkmark $ " , replace
qui estadd 	local ym  	" $ \checkmark $ " , replace
qui estadd 	local covar 	" $ \checkmark $  " , replace
qui estadd 	local sizeFE 	" $ \checkmark $ " , replace

qui eststo :xtreg annual_ear_prenot_def $instrument shareabove55_LOM $linear   $covariets2 $firmcovar $sizeFE , cluster(varselid) fe nonest
		test   	$instrument shareabove55_LOM
qui estadd 	scalar 	Fstat  = r(F), replace
qui estadd 	local lin  	" $ \checkmark $ " , replace
qui estadd 	local inter 	" $ \checkmark $ " , replace
qui estadd 	local ym  	" $ \checkmark $ " , replace
qui estadd 	local covar 	" $ \checkmark $ " , replace
qui estadd 	local Fcovar 	" $ \checkmark $ " , replace
qui estadd 	local sizeFE 	" $ \checkmark $ " , replace

qui eststo :xtreg annual_ear_prenot_def $instrument shareabove55_LOM $linear    $covariets2 $firmcovar $sizeFE  $ageinnot  , cluster(varselid) fe nonest
		test   	$instrument shareabove55_LOM
qui estadd 	scalar 	Fstat  = r(F), replace
qui estadd 	local lin  	" $ \checkmark $ " , replace
qui estadd 	local inter 	" $ \checkmark $ " , replace
qui estadd 	local ym  	" $ \checkmark $ " , replace
qui estadd 	local age 	" $ \checkmark $ " , replace
qui estadd 	local covar 	" $ \checkmark $ " , replace
qui estadd 	local Fcovar 	" $ \checkmark $ " , replace
qui estadd 	local sizeFE 	" $ \checkmark $ " , replace
qui estadd 	local ageinnot 	" $ \checkmark $ " , replace



xtset ym_def
qui eststo :xtreg annual_ear_prenot_def $instrument shareabove55_LOM $linear   $covariets2 $firmcovar $sizeFE D_SNI_1dig* , cluster(varselid) fe nonest
		test   	$instrument shareabove55_LOM
qui estadd 	scalar 	Fstat  = r(F), replace
qui estadd 	local lin  	" $ \checkmark $ " , replace
qui estadd 	local inter 	" $ \checkmark $ " , replace
qui estadd 	local ym  	" $ \checkmark $ " , replace
qui estadd 	local covar 	" $ \checkmark $ " , replace
qui estadd 	local Fcovar 	" $ \checkmark $ " , replace
qui estadd 	local sizeFE 	" $ \checkmark $ " , replace
qui estadd 	local ageinnot 	"  " , replace
qui estadd 	local SNI 	" $ \checkmark $ " , replace

xtset SNI_2dig
qui eststo :xtreg annual_ear_prenot_def $instrument shareabove55_LOM $linear   $covariets2 $firmcovar $sizeFE i.ym_def , cluster(varselid) fe nonest
		test   	$instrument shareabove55_LOM
qui estadd 	scalar 	Fstat  = r(F), replace
qui estadd 	local lin  	" $ \checkmark $ " , replace
qui estadd 	local inter 	" $ \checkmark $ " , replace
qui estadd 	local ym  	" $ \checkmark $ " , replace
qui estadd 	local covar 	" $ \checkmark $ " , replace
qui estadd 	local Fcovar 	" $ \checkmark $ " , replace
qui estadd 	local sizeFE 	" $ \checkmark $ " , replace
qui estadd 	local ageinnot 	"  " , replace
qui estadd 	local SNI2 	" $ \checkmark $ " , replace


esttab ,  se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) keep($instrument shareabove55_LOM _cons ) stats(Fstat N)
esttab using "$agetablepath/IV/tab_eartm1_largeIV.tex", replace keep($instrument shareabove55_LOM _cons ) booktabs nodepvars noobs nomtitles nonumbers ///
varlabels(N_above55 "Above 55" shareabove55_LOM "Share WC coworker above 55" _cons "Control mean") se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) ///
stats(fake lin  inter ym sizeFE  covar  Fcovar  ageinnot SNI SNI2  Fstat   N, ///
fmt(%9.0g %9.0g %9.0g %9.0g %9.0g  %9.0g %9.0g %9.0g %9.0g %9.0g   %9.3f   %9.0fc) /// 
labels("\textit{Polynomial order}" "\quad 1st degree"  "Interacted w. threshold" "Year/month FE" ///
"Size of layoff" "Basline covariates"  "Firm covariates" "Age shares controls" ///
 "1-letter industry" "2-digit industry"  "\addlinespace  F-statistic"  "Number of observations")) ///
title("Balancing Tests With Respect to Share Coworkers Above Age-55" ) ///
mlabels("(1)" "(2)" "(3)" "(4)" "(5)" "(6)"  ) ///
nonotes



restore
}
*

merge m:1 persid date using "$datapath/hist_v2.dta"
drop if _merge==2
drop _merge


gen contact = 0
forvalues i=1(1)5{
	replace kontakt_typ`i'=0 if kontakt_typ`i'==.
	replace contact = 1 if kontakt_typ`i'>=1 & contact==0	
}	

egen Ncontact = rowtotal(kontakt_typ*)



*keep if inrange(eventtime_def,0,24) | SP5_win_1_99!=.	

{ // Main table
*===============================================================================
*Generate: cumulative non-employment
bys lopnr (date) : egen cumnonemployed 	= total(atfirm2==0 & working2==0) 	if inrange(eventtime_def,1,24) 
bys lopnr (date) : gen  xdateotherfirm = date					if inrange(eventtime_def,1,24) & otherfirm2==1
bys lopnr (date) : egen dateofnewjob = min(xdateotherfirm)
			
*Search meassure
bys lopnr (date) : gen sumsearch = sum(Ncontact) 				if inrange(eventtime_def,0,24)  
bys lopnr (date) : gen sumsearch_arc = ln(sumsearch + sqrt(sumsearch^2 +1))

*Search meassure 2
gen Ncontact_censor =cond(otherfirm2==0,Ncontact,.)
bys lopnr (date) : gen sumserach_censor = sum(Ncontact_censor) 				if inrange(eventtime_def,0,24)  
gen sumsearch_arc_censor = ln(sumserach_censor + sqrt(sumserach_censor^2 +1))

*Extensive PES search
bys lopnr (date) : gen monthsatPES 	= sum(contact) 	if inrange(eventtime_def,0,24) 

gen timeuntilnewjob = dateofnewjob - notdate_def if eventtime_def<=24
format dateofnewjob %tm


bys lopnr (date) : gen haz = cond(date==dateofnewjob,1,cond(date>dateofnewjob,.,0))
bys lopnr (date) : egen haz_within2y = max(dateofnewjob!=.)

sum haz_within2y if eventtime_def==0
replace nottime_def= nottime_def/30 // make notification time in months


*Just get the number
preserve
keep if date==dateofnewjob & inrange(eventtime_def,1,24)
	sum monthsatPES
	ivreghdfe monthsatPES (nottime_def SP5IV = $instrument shareabove55_LOM) $linear   $covariets $firmcovar $sizeFE , cluster(varselid) absorb( ym_def SNI_2dig) 
restore
preserve
	keep if eventtime_def==1
	ivreghdfe haz_within2y (nottime_def SP5IV = $instrument shareabove55_LOM) $linear   $covariets $firmcovar $sizeFE , cluster(varselid) absorb( ym_def SNI_2dig) 
restore



*==========
xtset   ym_def
*==========
eststo clear
preserve
keep if eventtime_def==1
	qui eststo :xtreg nottime_def $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig, cluster(varselid) fe nonest
			test   	$instrument shareabove55_LOM
	qui estadd 	scalar 	Fstat  = r(F), replace
	qui estadd 	local lin  	" $ \checkmark $ " , replace
	qui estadd 	local inter 	" $ \checkmark $ " , replace
	qui estadd 	local ym  	" $ \checkmark $ " , replace
	qui estadd 	local covar 	" $ \checkmark $ " , replace
	qui estadd 	local Fcovar 	" $ \checkmark $ " , replace
	qui estadd 	local sizeFE 	" $ \checkmark $ " , replace
	qui estadd 	local ageinnot 	"  " , replace
	qui estadd 	local SNI2 	" $ \checkmark $ " , replace
restore
preserve
	qui eststo :xtreg SP5_win_1_99 $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig , cluster(varselid) fe nonest
			test   	$instrument shareabove55_LOM
	qui estadd 	scalar 	Fstat  = r(F), replace
	qui estadd 	local lin  	" $ \checkmark $ " , replace
	qui estadd 	local inter 	" $ \checkmark $ " , replace
	qui estadd 	local ym  	" $ \checkmark $ " , replace
	qui estadd 	local covar 	" $ \checkmark $ " , replace
	qui estadd 	local Fcovar 	" $ \checkmark $ " , replace
	qui estadd 	local sizeFE 	" $ \checkmark $ " , replace
	qui estadd 	local ageinnot 	"  " , replace
	qui estadd 	local SNI2 	" $ \checkmark $ " , replace
restore


preserve
keep if date==dateofnewjob & eventtime_def<=24
	 eststo :xtreg sumsearch_arc $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig , cluster(varselid) fe nonest
			test   	$instrument shareabove55_LOM		
	qui estadd 	scalar 	Fstat  = r(F), replace
	qui estadd 	local lin  	" $ \checkmark $ " , replace
	qui estadd 	local inter 	" $ \checkmark $ " , replace
	qui estadd 	local ym  	" $ \checkmark $ " , replace
	qui estadd 	local covar 	" $ \checkmark $ " , replace
	qui estadd 	local Fcovar 	" $ \checkmark $ " , replace
	qui estadd 	local sizeFE 	" $ \checkmark $ " , replace
	qui estadd 	local ageinnot 	"  " , replace
	qui estadd 	local SNI2 	" $ \checkmark $ " , replace
	
restore

preserve
keep if eventtime_def==1
	sum timeuntilnewjob,d
	 eststo :xtreg timeuntilnewjob $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig , cluster(varselid) fe nonest
			test   	$instrument shareabove55_LOM
	qui estadd 	scalar 	Fstat  = r(F), replace
	qui estadd 	local lin  	" $ \checkmark $ " , replace
	qui estadd 	local inter 	" $ \checkmark $ " , replace
	qui estadd 	local ym  	" $ \checkmark $ " , replace
	qui estadd 	local covar 	" $ \checkmark $ " , replace
	qui estadd 	local Fcovar 	" $ \checkmark $ " , replace
	qui estadd 	local sizeFE 	" $ \checkmark $ " , replace
	qui estadd 	local ageinnot 	"  " , replace
	qui estadd 	local SNI2 	" $ \checkmark $ " , replace
	
	qui eststo :xtreg cumnonemployed $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig , cluster(varselid) fe nonest
			test   	$instrument shareabove55_LOM
	qui estadd 	scalar 	Fstat  = r(F), replace
	qui estadd 	local lin  	" $ \checkmark $ " , replace
	qui estadd 	local inter 	" $ \checkmark $ " , replace
	qui estadd 	local ym  	" $ \checkmark $ " , replace
	qui estadd 	local covar 	" $ \checkmark $ " , replace
	qui estadd 	local Fcovar 	" $ \checkmark $ " , replace
	qui estadd 	local sizeFE 	" $ \checkmark $ " , replace
	qui estadd 	local ageinnot 	"  " , replace
	qui estadd 	local SNI2 	" $ \checkmark $ " , replace
restore

preserve
keep if   nvals==1 & eventtime_def<=24
	qui eststo :xtreg diff_log_manl_newfirm $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig , cluster(varselid) fe nonest
			test   	$instrument shareabove55_LOM
	qui estadd 	scalar 	Fstat  = r(F), replace
	qui estadd 	local lin  	" $ \checkmark $ " , replace
	qui estadd 	local inter 	" $ \checkmark $ " , replace
	qui estadd 	local ym  	" $ \checkmark $ " , replace
	qui estadd 	local covar 	" $ \checkmark $ " , replace
	qui estadd 	local Fcovar 	" $ \checkmark $ " , replace
	qui estadd 	local sizeFE 	" $ \checkmark $ " , replace
	qui estadd 	local ageinnot 	"  " , replace
	qui estadd 	local SNI2 	" $ \checkmark $ " , replace
restore
esttab ,  se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) keep($instrument shareabove55_LOM _cons ) stats(Fstat N)
esttab using "$agetablepath/IV/tab_IVest.tex", 				/// 
replace keep($instrument shareabove55_LOM) booktabs nodepvars  nomtitles nolines	nonumbers		///
varlabels(N_above55 "Above age-55" shareabove55_LOM "Share coworkers above 55" ) se(3) b(3)  			///
star(* 0.1 ** 0.05 *** 0.01)   	substitute(\_ _)							///
stats(  sizeFE    Fcovar    SNI2    Fstat r2_a N_clust N, ///
fmt(    %9.0g     %9.0g     %9.0g      %9.2f %9.3f %9.0fc %9.0fc) /// 
labels( "Layoff characteristics"   "Firm covariates"  ///
 "2-digit industry"  "\addlinespace Joint F-statistic" "$ R^2 $" "Number of clusters" "Number of observations")) ///
nonotes postfoot("\addlinespace ") prehead("\begin{table}[htbp] \centering \footnotesize" ///
"\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" ///
"\caption{Separating the Effects of Advance Notice and Severance Pay}" ///
"\begin{tabular}{l*{6}{c}}" ///
"\toprule" ///
"\textbf{Panel (a):}& \multicolumn{4}{c}{First-stage estimates} &\multicolumn{5}{c}{\textbf{Reduced-form estimates}} \\" ///	
"& \multicolumn{1}{c}{Notification time} & \multicolumn{1}{c}{Severance pay} & \multicolumn{1}{c}{Search} & \multicolumn{1}{c}{Months until}   & \multicolumn{1}{c}{Non-employment} & \multicolumn{1}{c}{ $ \Delta$ ln($ w $ )} \\ " ///
"& \multicolumn{1}{c}{(months)} & \multicolumn{1}{c}{(1,000 SEK)} & \multicolumn{1}{c}{ intensity }   & \multicolumn{1}{c}{new job }  & \multicolumn{1}{c}{(months)} & \multicolumn{1}{c}{  } \\ " ///
"&(1)&(2)&(3)&(4)&(5)&(6)&(7)&(8) \\" 	)		

*IV
eststo clear

preserve
keep if date==dateofnewjob & inrange(eventtime_def,1,24)
	qui eststo :ivreghdfe sumsearch_arc (nottime_def SP5IV = $instrument shareabove55_LOM) $linear   $covariets $firmcovar $sizeFE , cluster(varselid) absorb( ym_def SNI_2dig) 
	qui estadd 	scalar 	Fstat  = e(cdf), replace
	qui estadd 	local lin  	" $ \checkmark $ " , replace
	qui estadd 	local inter 	" $ \checkmark $ " , replace
	qui estadd 	local ym  	" $ \checkmark $ " , replace
	qui estadd 	local covar 	" $ \checkmark $ " , replace
	qui estadd 	local Fcovar 	" $ \checkmark $ " , replace
	qui estadd 	local sizeFE 	" $ \checkmark $ " , replace
	qui estadd 	local ageinnot 	"  " , replace
	qui estadd 	local SNI2 	" $ \checkmark $ " , replace

restore
preserve
keep if eventtime_def==1


	qui eststo :ivreghdfe timeuntilnewjob (nottime_def SP5IV = $instrument shareabove55_LOM) $linear   $covariets $firmcovar $sizeFE , cluster(varselid) absorb( ym_def SNI_2dig) 
	qui estadd 	scalar 	Fstat  = e(cdf), replace
	qui estadd 	local lin  	" $ \checkmark $ " , replace
	qui estadd 	local inter 	" $ \checkmark $ " , replace
	qui estadd 	local ym  	" $ \checkmark $ " , replace
	qui estadd 	local covar 	" $ \checkmark $ " , replace
	qui estadd 	local Fcovar 	" $ \checkmark $ " , replace
	qui estadd 	local sizeFE 	" $ \checkmark $ " , replace
	qui estadd 	local ageinnot 	"  " , replace
	qui estadd 	local SNI2 	" $ \checkmark $ " , replace

	qui eststo :ivreghdfe cumnonemployed (nottime_def SP5IV = $instrument shareabove55_LOM) $linear   $covariets $firmcovar $sizeFE , cluster(varselid) absorb( ym_def SNI_2dig) 
	qui estadd 	scalar 	Fstat  = e(cdf), replace
	qui estadd 	local lin  	" $ \checkmark $ " , replace
	qui estadd 	local inter 	" $ \checkmark $ " , replace
	qui estadd 	local ym  	" $ \checkmark $ " , replace
	qui estadd 	local covar 	" $ \checkmark $ " , replace
	qui estadd 	local Fcovar 	" $ \checkmark $ " , replace
	qui estadd 	local sizeFE 	" $ \checkmark $ " , replace
	qui estadd 	local ageinnot 	"  " , replace
	qui estadd 	local SNI2 	" $ \checkmark $ " , replace
restore

preserve
keep if   nvals==1 & eventtime_def<=24
	qui eststo :  ivreghdfe diff_log_manl_newfirm 	(nottime_def SP5IV = $instrument shareabove55_LOM) $linear     $covariets $firmcovar $sizeFE , cluster(varselid) absorb( ym_def SNI_2dig) 		

	qui estadd 	scalar 	Fstat  = e(cdf), replace
	qui estadd 	local lin  	" $ \checkmark $ " , replace
	qui estadd 	local inter 	" $ \checkmark $ " , replace
	qui estadd 	local ym  	" $ \checkmark $ " , replace
	qui estadd 	local covar 	" $ \checkmark $ " , replace
	qui estadd 	local Fcovar 	" $ \checkmark $ " , replace
	qui estadd 	local sizeFE 	" $ \checkmark $ " , replace
	qui estadd 	local ageinnot 	"  " , replace
	qui estadd 	local SNI2 	" $ \checkmark $ " , replace
restore

esttab ,  se(5) b(5) star(* 0.1 ** 0.05 *** 0.01) keep(nottime_def SP5IV  ) stats(Fstat N)
esttab using "$agetablepath/IV/tab_IVest.tex", 	///
append 	keep(nottime_def SP5IV ) booktabs 		///
nodepvars  nomtitles nolines	nonumbers		///
stats(  Fstat   N, ///
fmt(    %9.3f  %9.0fc) /// 
labels( "Joint F-statistic" "Number of observations")) ///
	varlabels(nottime_def "Notification time (months)" SP5IV "Severance pay (1,000 SEK)" ) ///
prehead("\textbf{Panel (b):} & \multicolumn{4}{c}{} & \multicolumn{5}{c}{\textbf{Instrumental variabels estimates}} \\ " ///
"\cmidrule(lr){6-9}" ) ///
end("\\") begin("")  nonumbers nodepvar  nogaps nolines nomtitles ///
se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) ///
postfoot("\bottomrule \end{tabular} \end{table}")

}
*

{ // RF: Search and hazard graph
keep if inrange(eventtime_def,0,24)
matrix A = J(25,4,.)
matrix B = J(25,4,.)
matrix C = J(25,4,.)
forvalues t = 0(1)24{
	preserve
		keep if eventtime_def==`t'
		local i = `i' +1
		
		qui xtreg sumsearch_arc $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig , cluster(varselid) fe nonest
		matrix A[`i',1] = _b[$instrument]
		matrix A[`i',2] = _b[$instrument] + 1.96*_se[$instrument] 
		matrix A[`i',3] = _b[$instrument] - 1.96*_se[$instrument] 
		matrix A[`i',4] = `t'
		
		*qui xtreg sumsearch_arc_censor $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig , cluster(varselid) fe nonest
		*matrix B[`i',1] = _b[$instrument]
		*matrix B[`i',2] = _b[$instrument] + 1.96*_se[$instrument] 
		*matrix B[`i',3] = _b[$instrument] - 1.96*_se[$instrument] 
		*matrix B[`i',4] = `t'
		
		qui xtreg haz $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig , cluster(varselid) fe nonest
		matrix C[`i',1] = _b[$instrument]
		matrix C[`i',2] = _b[$instrument] + 1.96*_se[$instrument] 
		matrix C[`i',3] = _b[$instrument] - 1.96*_se[$instrument] 
		matrix C[`i',4] = `t'
		
	restore	
}	

svmat A
*svmat B
svmat C

preserve
	gcollapse (mean) A1-A3  C*, by(A4)
	*replace B4 = B4 - .25
	replace C4 = C4 + .25
	twoway 	(scatter A1 A4, ms(o)  mcolor(black) ) ///
		(scatter C1 A4, ms(t)  mcolor(navy)  ) ///
		(rcap A2 A3 A4, lpattern(dash) lcolor(black) lstyle(foreground)) ///
		(rcap C2 C3 A4, lpattern(dash) lcolor(navy) lstyle(foreground)) ///
	, yline(0, lcolor(black) lpattern(dash) lstyle(foreground)) ///
	graphregion(color(white)) legend(order( 1 "Cumulated search"  2 "Hazard") col(3) region(color(white))) ///
	xtitle("Months relative to notification") ytitle("Above age-55 {&beta}-estimate") xscale(r(0 24)) xlab(0(3)24) 
restore

graph export "$agegraphpath/IV/RF_serach_hazard.pdf",replace

}	
*



{ // First stages for col. 3-6 in IV-table
*===============================================================================

*==========
xtset   ym_def
*==========
eststo clear
preserve
keep if date==dateofnewjob & inrange(eventtime_def,1,24)
	qui  ivreghdfe sumsearch_arc (nottime_def SP5IV = $instrument shareabove55_LOM) $linear   $covariets $firmcovar $sizeFE , cluster(varselid) absorb( ym_def SNI_2dig) 
	keep if e(sample)==1

	qui eststo :xtreg nottime_def $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig, cluster(varselid) fe nonest
			test   	$instrument shareabove55_LOM
	qui estadd 	scalar 	Fstat  = r(F), replace

	qui eststo :xtreg SP5IV $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig , cluster(varselid) fe nonest
			test   	$instrument shareabove55_LOM
	qui estadd 	scalar 	Fstat  = r(F), replace

	esttab ,keep($instrument shareabove55_LOM) se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) stats(cdf Fstat N) 
restore
	
	

preserve
keep if eventtime_def==1
	qui ivreghdfe timeuntilnewjob (nottime_def SP5IV = $instrument shareabove55_LOM) $linear   $covariets $firmcovar $sizeFE , cluster(varselid) absorb( ym_def SNI_2dig)  ffirst
	keep if e(sample)==1

	qui eststo :xtreg nottime_def $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig, cluster(varselid) fe nonest
			test   	$instrument shareabove55_LOM
	qui estadd 	scalar 	Fstat  = r(F), replace

	qui eststo :xtreg SP5IV $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig , cluster(varselid) fe nonest
			test   	$instrument shareabove55_LOM
	qui estadd 	scalar 	Fstat  = r(F), replace

	esttab ,keep($instrument shareabove55_LOM) se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) stats(cdf Fstat N) 
restore
	

preserve
keep if eventtime_def==1
	qui  ivreghdfe cumnonemployed (nottime_def SP5IV = $instrument shareabove55_LOM) $linear   $covariets $firmcovar $sizeFE , cluster(varselid) absorb( ym_def SNI_2dig) 
	keep if e(sample)==1

	qui eststo :xtreg nottime_def $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig, cluster(varselid) fe nonest
			test   	$instrument shareabove55_LOM
	qui estadd 	scalar 	Fstat  = r(F), replace

	qui eststo :xtreg SP5IV $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig , cluster(varselid) fe nonest
			test   	$instrument shareabove55_LOM
	qui estadd 	scalar 	Fstat  = r(F), replace

	esttab ,keep($instrument shareabove55_LOM) se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) stats(cdf Fstat N) 
restore
		

		
preserve
keep if   nvals==1 & eventtime_def<=24
	qui   ivreghdfe diff_log_manl_newfirm 	(nottime_def SP5IV = $instrument shareabove55_LOM) $linear     $covariets $firmcovar $sizeFE , cluster(varselid) absorb( ym_def SNI_2dig) 		
	keep if e(sample)==1

	qui eststo :xtreg nottime_def $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig, cluster(varselid) fe nonest
			test   	$instrument shareabove55_LOM
	qui estadd 	scalar 	Fstat  = r(F), replace

	qui eststo :xtreg SP5IV $instrument shareabove55_LOM $linear   $covariets $firmcovar $sizeFE i.SNI_2dig , cluster(varselid) fe nonest
			test   	$instrument shareabove55_LOM
	qui estadd 	scalar 	Fstat  = r(F), replace

	
restore

esttab ,keep($instrument shareabove55_LOM) se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) stats(cdf Fstat N) 
esttab using "$agetablepath/IV/tab_IVest_firststages.tex", 				/// 
replace keep($instrument shareabove55_LOM) booktabs nodepvars  nomtitles nolines	nonumbers		///
varlabels(N_above55 "Above age-55" shareabove55_LOM "Share coworkers above 55" ) se(3) b(3)  			///
star(* 0.1 ** 0.05 *** 0.01)   	substitute(\_ _)							///
stats(  Fstat  N_clust N, ///
fmt(      %9.0g      %9.0fc %9.0fc) /// 
labels(  " Joint F-statistic" "Number of clusters" "Number of observations")) ///
nonotes prehead("\begin{table}[htbp] \centering \footnotesize" ///
"\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" ///
"\caption{First Stage Estimates of Advance Notice and Severance Pay}" ///
"\begin{tabular}{l*{8}{c}}" ///
"\toprule" /// 
"& \multicolumn{2}{c}{Search intensity} & \multicolumn{2}{c}{Months until new job} & \multicolumn{2}{c}{Non-employment} & \multicolumn{2}{c}{ $ \Delta ln(w) $ }  \\" ///	 
"& \multicolumn{1}{c}{Notification} & \multicolumn{1}{c}{Severance}& \multicolumn{1}{c}{Notification} & \multicolumn{1}{c}{Severance}& \multicolumn{1}{c}{Notification} & \multicolumn{1}{c}{Severance}& \multicolumn{1}{c}{Notification} & \multicolumn{1}{c}{Severance} \\" ///
"& \multicolumn{1}{c}{time (months)} & \multicolumn{1}{c}{(1,000 SEK)} & \multicolumn{1}{c}{time (months)} & \multicolumn{1}{c}{(1,000 SEK)} & \multicolumn{1}{c}{time (months)} & \multicolumn{1}{c}{(1,000 SEK)} & \multicolumn{1}{c}{time (months)} & \multicolumn{1}{c}{(1,000 SEK)} \\ " ///
"&(1)&(2)&(3)&(4)&(5)&(6)&(7)&(8) \\" 	)	///	
postfoot("\bottomrule \end{tabular} \end{table}")

}
*
	
